package com.zadtek.sharkRider.activity;

import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.ResultReceiver;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.vision.barcode.Barcode;
import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.adapter.OrderNewAdapter;
import com.zadtek.sharkRider.activity.adapter.OrderNewHelpAdapter;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.NewOrderData;
import com.zadtek.sharkRider.activity.data.OrderNewData;
import com.zadtek.sharkRider.activity.data.OrderNewHelpData;
import com.zadtek.sharkRider.activity.data.QiangDanData;
import com.zadtek.sharkRider.activity.data.Timebean;
import com.zadtek.sharkRider.frame.JsonProcessHelper;
import com.zadtek.sharkRider.util.gmap.Address;
import com.zadtek.sharkRider.util.gmap.AddressService;
import com.zadtek.sharkRider.util.gmap.GLocation;
import com.zadtek.sharkRider.views.GetOrderNum;
import com.zadtek.sharkRider.views.LazyScrollView;
import com.zadtek.sharkRider.views.MyListView;
import com.zadtek.sharkRider.views.OnChanged;


import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 新任务
 * 
 * @author Administrator
 * 
 */
public class OrdernewActivity extends BaseActivity implements OnChanged, AMapLocationListener,OnMapReadyCallback {
	private MyListView newtaskList;
	private MyListView helpList;
	private LinearLayout ordernewlayout, flush;
	OrderNewAdapter newadapter;
	OrderNewHelpAdapter helpadapter;

	// private ArrayList<OrderNewData> OrderNewList = new
	// ArrayList<OrderNewData>();
	NewOrderData OrderDatas = new NewOrderData();
	OrderAsyncTask mOrderAsyn;
	private QiangDanData qiangdan;
	public static Handler mHandler;
	private String Uid = "";
	private SharedPreferences sp; // 用户信息缓存
	private Editor editor;

	private LazyScrollView waterfall_scroll;
	private View mHeaderView;// 头部的控件
	private TextView pulldown_header_text; // 头部面板
	private ProgressBar progress_loading;
	GetOrderNum numlisenter;

	//屏蔽 换谷歌
   /*private AMap aMap;
	// 声明mLocationOption对象
	public AMapLocationClientOption mLocationOption = null;
	private AMapLocationClient mlocationClient;*/
	PowerManager pm;
	WakeLock mWakeLock;
	private boolean isFlush = false;// 是否一直刷新
	private boolean isFlush1 = false;// 是否一直抢单
	private static String mRrlastid = "0";
	private static String mHelplastid = "0";

	private ArrayList<OrderNewData> orderlist; // 普通订单列表
	private ArrayList<OrderNewHelpData> orderhelplist; // 普通订单列表

	private int Orderid = -1;
	private int Orderhelpid = -1;

	Timebean time;
	private Timer timer;
	private TimerTask timerTask;
	String ts, ts1;// 倒计时时间
	Date curDate;
	private int recLen = 11;

	private void setDiffss() {
		if (timerTask == null) {
			timerTask = new TimerTask() {

				@Override
				public void run() {
					Message message = Message.obtain();
					message.what = Const.STATE_ENDTIME_SUCCESS;
					mHandler.sendMessage(message);
				}
			};
		}
		timer = new Timer();
		timer.schedule(timerTask, 1000, 1000);

	}

	// 设置倒计时view
	private void getHmsecd() {
		if (newadapter != null) {
			newadapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newtasklist);

		pm = (PowerManager) getSystemService(Service.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");

		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		Uid = sp.getString("uid", "");
		newtaskList = (MyListView) findViewById(R.id.newtasklist);
		helpList = (MyListView) findViewById(R.id.helplist);
		ordernewlayout = (LinearLayout) findViewById(R.id.ordernewlayout);
		flush = (LinearLayout) findViewById(R.id.flush);
		progress_loading = (ProgressBar) findViewById(R.id.progress_loading);
		progress_loading.setVisibility(View.GONE);
		waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);
		/**
		 * 头部和底部刷新
		 */
		mHeaderView = findViewById(R.id.mHeaderView);
		pulldown_header_text = (TextView) findViewById(R.id.pulldown_header_text);
		pulldown_header_text.setText("刷新中...");

		Const.ORDER_FLAGS = 0;
		flush.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (isFlush == false) {
					progress_loading.setVisibility(View.VISIBLE);
					// ProgressBar背后的第二个进度条 进度值减少5
					if (Common.isNetworkConnected(OrdernewActivity.this)) {
						isFlush = true;
						mHeaderView.setVisibility(View.VISIBLE);
						mOrderAsyn = new OrderAsyncTask();
						mOrderAsyn.execute("newlist");

						mOrderAsyn = new OrderAsyncTask();
						mOrderAsyn.execute("location");
					} else {
						closeProgressDialog();
						Common.DisplayToast(OrdernewActivity.this,
								"通信失败,请检查网络!", 1);
						isFlush = false;
					}
				}
			}
		});


		//屏蔽百度定位 换谷歌
		/*mlocationClient = new AMapLocationClient(this);
		// 初始化定位参数
		mLocationOption = new AMapLocationClientOption();
		// 设置定位监听
		mlocationClient.setLocationListener(this);
		// 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		// 设置定位间隔,单位毫秒,默认为2000ms
		mLocationOption.setInterval(5000);
		// 设置定位参数
		mlocationClient.setLocationOption(mLocationOption);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用onDestroy()方法
		// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
		// 启动定位
		mlocationClient.startLocation();*/

		gLocation = new GLocation(this){
			@Override
			protected void successful(double lng, double lat) {
				super.successful(lng, lat);
				Common.DisplayToast(OrdernewActivity.this, "google定位  lng:"+lng  +"  lat:"+ lat, 1);
				onLocationSuccessful(lng,lat);
			}

			@Override
			protected void failure(String msg) {
				super.failure(msg);
				Common.DisplayToast(OrdernewActivity.this, "google定位失败,请检查网络!", 1);
			}
		};


		if (Common.isNetworkConnected(OrdernewActivity.this)) {
			helpList.setVisibility(View.VISIBLE);
			newtaskList.setVisibility(View.VISIBLE);
			ordernewlayout.setVisibility(View.GONE);
			// showProgressDialog("数据加载中...");
			mHeaderView.setVisibility(View.VISIBLE);
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("newlist");

		} else {
			closeProgressDialog();
			Common.DisplayToast(OrdernewActivity.this, "通信失败,请检查网络!", 1);
		}

		mHandler = new Handler() {
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case Const.STATE_ENDTIME_SUCCESS:

					if (OrderDatas != null
							&& OrderDatas.getOrdernewdata() != null) {
						for (int i = 0; i < OrderDatas.getOrdernewdata().size(); i++) {
							if (OrderDatas.getOrdernewdata() != null
									&& OrderDatas.getOrdernewdata().get(i)
											.getTime_limit() != null
									&& Long.valueOf(OrderDatas
											.getOrdernewdata().get(i)
											.getTime_limit()) > 0) {
								OrderDatas
										.getOrdernewdata()
										.get(i)
										.setTime_limit(
												Long.valueOf(OrderDatas
														.getOrdernewdata()
														.get(i).getTime_limit())
														- 1 + "");
							} else {
								OrderDatas.getOrdernewdata().get(i)
										.setTime_limit("0");
							}
							getHmsecd();
						}
					}

					break;
				case Const.STATE_START_SUCCESS://
					closeProgressDialog();
					isFlush = false;
					OrderDatas = new NewOrderData();
					OrderDatas = (NewOrderData) msg.obj;
					mHeaderView.setVisibility(View.GONE);
					progress_loading.setVisibility(View.GONE);
					if (timerTask != null) {
						timerTask.cancel();
						timerTask = null;
					}
					try {
						if (OrderDatas != null && !OrderDatas.equals("")
								&& !OrderDatas.equals("null")) {
							orderlist = OrderDatas.getOrdernewdata();
							orderhelplist = OrderDatas.getNewhelpData();
							if ((orderlist != null
									&& orderlist.get(0).getStatus01() != null && !orderlist
									.get(0).getStatus01().equals("0"))
									|| (orderhelplist != null
											&& orderhelplist.get(0).getStatus() != null && !orderhelplist
											.get(0).getStatus().equals("0"))) {

								mRrlastid = OrderDatas.getRr_last_id();// 获取人人便利最后的id
								mHelplastid = OrderDatas.getHelp_last_id();// 获取随意购最后的id

								if (orderlist != null
										&& !orderlist.get(0).getStatus01()
												.equals("0")) {
									getGpsaddr(); // 根据坐标反查地址
									newtaskList.setVisibility(View.VISIBLE);

									ordernewlayout.setVisibility(View.GONE);
									setDiffss(); // 设置倒计时的时间
									for (int i = 0; i < orderlist.size(); i++) {
										OrderNewData dataobj = orderlist.get(i);
										dataobj.setmPosition("");
										orderlist.set(i, dataobj);
										OrderDatas.setOrdernewdata(orderlist);
									}
									newadapter = new OrderNewAdapter(
											OrdernewActivity.this, orderlist,
											R.layout.newtasklist_item);
									newadapter
											.setOnChanged(OrdernewActivity.this);
									newtaskList.setAdapter(newadapter);

								} else {
									newtaskList.setVisibility(View.GONE);
								}
								if (orderhelplist != null
										&& !orderhelplist.get(0).getStatus()
												.equals("0")) {
									helpList.setVisibility(View.VISIBLE);
									ordernewlayout.setVisibility(View.GONE);

									for (int i = 0; i < orderhelplist.size(); i++) {
										OrderNewHelpData dataobj = orderhelplist
												.get(i);
										dataobj.setmHelpposition("");
										orderhelplist.set(i, dataobj);
										OrderDatas
												.setNewhelpData(orderhelplist);
									}

									helpadapter = new OrderNewHelpAdapter(
											OrdernewActivity.this,
											orderhelplist,
											R.layout.helplist_item);
									helpadapter
											.setHelpOnChanged(OrdernewActivity.this);
									helpList.setAdapter(helpadapter);

								} else {
									helpList.setVisibility(View.GONE);
								}
								InitLayout();

							} else {
								helpList.setVisibility(View.GONE);
								newtaskList.setVisibility(View.GONE);
								ordernewlayout.setVisibility(View.VISIBLE);
							}
						} else {
							Common.DisplayToast(OrdernewActivity.this,
									"数据加载失败!", 1);
						}

					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					break;
				case Const.STATE_START_QIANG://
					isFlush1 = false;
					closeProgressDialog();
					qiangdan = new QiangDanData();
					qiangdan = (QiangDanData) msg.obj;
					try {
						if (null != qiangdan) {
							if (null != qiangdan.getStatus()) {

								if (qiangdan.getStatus().equals("1")) {
								
									Common.DisplayToast(OrdernewActivity.this,
											qiangdan.getMessage(), 1);
									int size = OrderDatas.getOrdernewdata()
											.size();
									for (int i = 0; i < size; i++) {
										if (Orderid != -1 && Orderid == i) {
											orderlist.remove(Orderid);
											if (newadapter != null) {
												newadapter
												.notifyDataSetChanged();
											}
										}
									}
									if (Common
											.isNetworkConnected(OrdernewActivity.this)) {
										new OrderAsyncTask().execute("getsum");

									} else {
										closeProgressDialog();
										Common.DisplayToast(
												OrdernewActivity.this,
												"通信失败,请检查网络!", 1);
									}
								} else if (qiangdan.getStatus().equals("99")) {
									if (OrderDatas != null
											&& OrderDatas.getOrdernewdata() != null) {
										for (int i = 0; i < OrderDatas
												.getOrdernewdata().size(); i++) {
												if (Orderid != -1 && Orderid == i) {
												long time1 =Long.valueOf(OrderDatas.getOrdernewdata().get(i).getTime_limit());
												long time2 =Long.valueOf(qiangdan.getReturn_time());
													if(!OrderDatas
															.getOrdernewdata()
															.get(i).getTime_limit().equals(qiangdan.getReturn_time()) && time1>time2){
												OrderDatas
														.getOrdernewdata()
														.get(i)
														.setTime_limit(
																Long.valueOf(qiangdan.getReturn_time())
																		+ "");
												getHmsecd();
													}
											} 
										}
									}
								} else if (qiangdan.getStatus().equals("0")) {
									int size = OrderDatas.getOrdernewdata()
											.size();
									for (int i = 0; i < size; i++) {
										if (Orderid != -1 && Orderid == i) {
											orderlist.remove(Orderid);
											if (newadapter != null) {
												newadapter
														.notifyDataSetChanged();
											}
										}
									}
								}
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case Const.STATE_SETQS_OPEN://
					closeProgressDialog();
					qiangdan = new QiangDanData();
					qiangdan = (QiangDanData) msg.obj;
					try {
						if (null != qiangdan) {
							if (null != qiangdan.getStatus()) {
								if (qiangdan.getStatus().equals("200")) {
									Common.DisplayToast(OrdernewActivity.this,
											qiangdan.getMessage(), 1);
									
									int size = OrderDatas.getNewhelpData()
											.size();
									for (int i = 0; i < size; i++) {
										if (Orderhelpid != -1
												&& Orderhelpid == i) {
											orderhelplist.remove(i);
											if (helpadapter != null) {
												helpadapter
												.notifyDataSetChanged();
											}
										}
									}
									if (Common
											.isNetworkConnected(OrdernewActivity.this)) {
										new OrderAsyncTask().execute("getsum");
									} else {
										closeProgressDialog();
										Common.DisplayToast(
												OrdernewActivity.this,
												"通信失败,请检查网络!", 1);
									}
								} else if (qiangdan.getStatus().equals("0")) {
									int size = OrderDatas.getNewhelpData()
											.size();
									for (int i = 0; i < size; i++) {
										try {
											if (Orderhelpid != -1
													&& Orderhelpid == i) {
												orderhelplist.remove(i);
												if (helpadapter != null) {
													helpadapter
															.notifyDataSetChanged();
												}
											}

										} catch (Exception e) {
										}
									}
								}
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case Const.STATE_START_LOCATION://
					closeProgressDialog();
					qiangdan = new QiangDanData();
					qiangdan = (QiangDanData) msg.obj;
					if (null != qiangdan && null != qiangdan.getStatus()) {
						if (qiangdan.getStatus().equals("0")) {
							Common.DisplayToast(OrdernewActivity.this,
									qiangdan.getMessage(), 1);
						}
					}

					break;
				case Const.STATE_START_ERROR://
					isFlush = false;
					isFlush1 = false;
					closeProgressDialog();
					Common.DisplayToast(OrdernewActivity.this, "获取数据失败", 1);
					break;
				case Const.STATE_GETNUM_SUCC: // 获取数量成功
					QiangDanData sumcout = (QiangDanData) msg.obj;
					String status = sumcout.getStatus();
					if (status != null && status.equals("1")) {
						String xincount = sumcout.getNeworder();
						String noget = sumcout.getNoget();
						String nosend = sumcout.getNosend();
						MainActivity.radio_goqh.setText("待取货(" + noget + ")");
						MainActivity.radio_gops.setText("配送中(" + nosend + ")");
					}
					break;
				case Const.STATE_GETNUM_FAIL:
					// Common.DisplayToast(MainActivity.this, "通信失败,请检查网络!", 2);
					break;
				case 0x111:
					if (Const.ORDER_FLAGS == 0) {
						mOrderAsyn = new OrderAsyncTask();
						mOrderAsyn.execute("newlist");
					}
					break;
				}
			}
		};

		mHandler.postDelayed(thread, 60000);// 使用Handler启动Runnable(3s后)

	}

	// 根据经纬度获取地址
	private void getGpsaddr() {
		int size = orderlist.size();
		for (int i = 0; i < size; i++) {
			try {
				OrderNewData dataobj = orderlist.get(i);
				String phoneaddr = dataobj.getOrderItemList().get(0)
						.getPhone_addr();
				String address_road = dataobj.getAddress_road();
				if (address_road == null || address_road.equals("")
						|| address_road.equals("null")) {

					if (phoneaddr != null && !phoneaddr.equals("")
							&& !phoneaddr.equals("null")) {
						String[] latlng = phoneaddr.split(",");
						double lng = Double.parseDouble(latlng[0]);
						double lat = Double.parseDouble(latlng[1]);
						getgpssAddress(lat, lng, dataobj, i);
					}
				}

			} catch (Exception e) {
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mWakeLock.acquire();
		gLocation.onResume();
	}

	// 初始化面板
	private void InitLayout() {
		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new LazyScrollView.OnScrollListener() {

			@Override
			public void onTop() {
				mHeaderView.setVisibility(View.VISIBLE);
				isFlush = false;
				if (Common.isNetworkConnected(OrdernewActivity.this)) {
					// showProgressDialog("数据加载中...");
					mHeaderView.setVisibility(View.VISIBLE);
					mOrderAsyn = new OrderAsyncTask();
					mOrderAsyn.execute("newlist");
					isFlush = false;
				} else {
					closeProgressDialog();
					Common.DisplayToast(OrdernewActivity.this, "通信失败,请检查网络!", 1);
				}
			}

			@Override
			public void onScroll() {
				// 滚动中
			}

			@Override
			public void onBottom() {
			}
		});
	}

	class OrderAsyncTask extends AsyncTask<String, String, String> {

		private QiangDanData countdata;

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String res = "";
			if (params[0].equals("newlist")) {// 新任务列表数据
				if (mHandler != null) {
					mHandler.removeCallbacks(timerTask);
				}
				if (timer != null) {
					timer.cancel();
					timer = null;
				}
				sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
				String uid = sp.getString("uid", "");
				OrderDatas = new NewOrderData();
				OrderDatas = JsonProcessHelper.jsonProcess_getOrderList(
						"get_rr_help_order_list", Const.latitude,
						Const.lontitude, uid, mRrlastid, mHelplastid);
				// lng":"112.769327","lat":"32.13676"
				if (OrderDatas != null) {
					res = "state_success";
				} else {
					res = "mi_error";
				}
			} else if (params[0].equals("qiangdan")) {// 点击抢单
				qiangdan = new QiangDanData();
				qiangdan = JsonProcessHelper.jsonProcess_getQsQiang("qs_qiang",
						params[1], params[2]);
//				 qiangdan = JsonProcessHelper.jsonProcess_getQsQiang(
//				 "qs_qiang_temp", params[1], params[2]);
				if (qiangdan != null) {
					res = "state_qiang";
				} else {
					res = "mi_error";
				}
			} else if (params[0].equals("ex_qiangdan")) {// 随意购点击抢单
				qiangdan = new QiangDanData();
				qiangdan = JsonProcessHelper.jsonProcess_getHelpQsQiang(
						"ex_qiang", params[1], params[2]);
				if (qiangdan != null) {
					res = "state_qiang1";
				} else {
					res = "mi_error";
				}
			} else if (params[0].equals("location")) {// 更新骑士坐标
				if (Const.latitude.length() > 0 && Const.lontitude.length() > 0
						&& !Const.latitude.equals("0")
						&& !Const.lontitude.equals("0")
						&& !Const.lontitude.contains("E")
						&& !Const.latitude.contains("E")) {

					qiangdan = new QiangDanData();
					qiangdan = JsonProcessHelper.jsonProcess_setEmpLocation(
							"set_emp_location", Uid, Const.latitude,
							Const.lontitude);// emp_id(快递ID)，lat(纬度)，lng(经度)
					if (qiangdan != null) {
						res = " ";
					} else {
						res = "mi_error";
					}
				}
			} else if (params[0].equals("getsum")) { // 获取数量

				sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
				String uid = sp.getString("uid", "");
				countdata = JsonProcessHelper.jsonProcess_getOrderCount(
						"get_order_count", uid);
				if (null != countdata) {
					res = "get_ok";
				} else {
					res = "ping_me_error";
				}

			}
			return res;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result.equals("state_success")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_SUCCESS;
				msg.obj = OrderDatas;
				mHandler.sendMessage(msg);
			} else if (result.equals("state_qiang")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_QIANG;
				msg.obj = qiangdan;
				mHandler.sendMessage(msg);
			} else if (result.equals("state_qiang1")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_SETQS_OPEN;
				msg.obj = qiangdan;
				mHandler.sendMessage(msg);
			} else if (result.equals("state_location")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_LOCATION;
				msg.obj = qiangdan;
				mHandler.sendMessage(msg);
			} else if (result.equals("mi_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_ERROR;
				mHandler.sendMessage(msg);
			} else if (result.equals("get_ok")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_GETNUM_SUCC;
				msg.obj = countdata;
				mHandler.sendMessage(msg);
			} else if (result.equals("ping_me_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_GETNUM_FAIL;
				mHandler.sendMessage(msg);
			}
		}
	}

	@Override
	public void getChoiceData(String mainid, String empid, int position) {
		// showProgressDialog("数据加载中...");
		if (isFlush1 == false) {
			if (Common.isNetworkConnected(OrdernewActivity.this)) {
				isFlush1 = true;
				Orderid = position;
				mOrderAsyn = new OrderAsyncTask();
				mOrderAsyn.execute("qiangdan", mainid, empid);
			} else {
				closeProgressDialog();
				Common.DisplayToast(OrdernewActivity.this, "通信失败,请检查网络!", 1);
				isFlush1 = false;
			}
		}
	}

	@Override
	public void getHelpChoiceData(String orderid, String empid, int position) {
		// showProgressDialog("数据加载中...");
		if (Common.isNetworkConnected(OrdernewActivity.this)) {
			Orderhelpid = position;
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("ex_qiangdan", orderid, empid);
		} else {
			closeProgressDialog();
			Common.DisplayToast(OrdernewActivity.this, "通信失败,请检查网络!", 1);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//mlocationClient.stopLocation();// 停止定位
		mHandler.removeCallbacks(thread);
		mHandler.removeCallbacks(timerTask);
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (amapLocation != null) {
			if (amapLocation.getErrorCode() == 0
					&& Common.isNetworkConnected(OrdernewActivity.this)) {
				// 定位成功回调信息，设置相关消息
				// amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
				amapLocation.getLatitude();// 获取纬度
				amapLocation.getLongitude();// 获取经度
				amapLocation.getAccuracy();// 获取精度信息
				if (amapLocation.getLatitude() > 0
						&& amapLocation.getLongitude() > 0) {
					LatLng lng1 = new LatLng(amapLocation.getLatitude(),
							amapLocation.getLongitude());
					LatLng lng2 = new LatLng(
							Double.parseDouble(Const.latitude),
							Double.parseDouble(Const.lontitude));
					float distance = AMapUtils
							.calculateLineDistance(lng1, lng2);
					if (!Const.latitude.equals(amapLocation.getLatitude() + "")
							&& !Const.lontitude.equals(amapLocation
									.getLongitude() + "")) {
						Const.latitude = amapLocation.getLatitude() + "";
						Const.lontitude = amapLocation.getLongitude() + "";
						if (distance > 100) {
							mOrderAsyn = new OrderAsyncTask();
							mOrderAsyn.execute("location");
						}
					}
				}
			} else {
				closeProgressDialog();
				Common.DisplayToast(OrdernewActivity.this, "定位失败,请检查网络!", 1);

			}
		}
	}

	public void setNumlisenter(GetOrderNum numlisenter) {
		this.numlisenter = numlisenter;
	}

	Thread thread = new Thread(new Runnable() {
		@Override
		public void run() {
			Message message = new Message();
			message.what = 0x111;
			mHandler.sendMessage(message);
			mHandler.postDelayed(this, 60000);// 3s后执行
		}
	});

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// mHandler.removeCallbacks(thread);
		mWakeLock.release();
		gLocation.onPause();
	}

	// 反查的
	void getgpssAddress(double lat, double lng, final OrderNewData dataobj,
			final int positon) {
		GeocodeSearch geocoderSearch = new GeocodeSearch(this);
		geocoderSearch
				.setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
					@Override
					public void onGeocodeSearched(GeocodeResult result,
							int rCode) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onRegeocodeSearched(RegeocodeResult result,
							int rCode) {
						if (rCode == 1000) {
							String formatAddress = result.getRegeocodeAddress()
									.getFormatAddress();
							try {
								dataobj.setGps_addrs(formatAddress);
								orderlist.set(positon, dataobj);
								OrderDatas.setOrdernewdata(orderlist);
								if (newadapter != null) {
									newadapter.notifyDataSetChanged();
								}
							} catch (Exception e) {
							}
						}
					}
				});
		LatLonPoint lp = new LatLonPoint(lat, lng);
		RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}


	private GoogleMap mMap;
	private GLocation gLocation;
	// 纬度,经度
	private double Latitude = 0.0, Longitude = 0.0;


	private ResultReceiver mReceiver = new ResultReceiver(new Handler(Looper.getMainLooper())){
		@Override
		protected void onReceiveResult(int resultCode, final Bundle bundle) {
			super.onReceiveResult(resultCode, bundle);

			if (resultCode == AddressService.RESULT_FAILURE) {
				final String msg = bundle.getString(AddressService.EXTRA_FAILURE);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {


					}
				});
			} else if(resultCode == AddressService.RESULT_SUCCESS) {
				final ArrayList<Address> addresses = bundle.getParcelableArrayList(AddressService.EXTRA_ADDRESS);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {

					}
				});
			}
		}
	};

	protected void onLocationSuccessful(double lng, double lat) {
		Latitude = lat;// 获取纬度
		Longitude = lng;// 获取经度
		Const.latitude = String.valueOf(lat);
		Const.lontitude = String.valueOf(lng);
		AddressService.fromNearby(OrdernewActivity.this,mReceiver,lng,lat);
	}

	@Override
	public void onMapReady(GoogleMap googleMap) {
		mMap = googleMap;
		mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
		mMap.setTrafficEnabled(true);
		mMap.getUiSettings().setZoomControlsEnabled(true);
		mMap.getUiSettings().setZoomGesturesEnabled(true);
		gLocation.onMapReady(mMap);
	}

	@Override
	public void onStart() {
		super.onStart();
		gLocation.onStart();
	}

	@Override
	public void onStop() {
		super.onStop();
		gLocation.onStop();
	}




}
